const express = require('express')
const {
    ValidationError
} = require("express-validation")
const cors = require('cors')
const fs = require('fs')
const jwt = require('jsonwebtoken')

const dayjs = require('dayjs')

const userRouter = require('./routers/User')
const articleRouter = require('./routers/Article')
const cateRouter = require('./routers/Cate')
//引入路由
//使用路由
const app = express()
app.use(express.static('uploads'))

// 配置跨域
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({
    extended: false
}))

// 配置解析token中间件
const expressJWT = require("express-jwt")
const config = require('./config/index')


app.use(expressJWT({
    secret: config.jwtSecretKey,
    algorithms: ['HS256']
}).unless({
    path: [/^\/api\//, /^\/uploads\//]
}))

//暴漏静态资源文件 暴漏之后我们可以通过域名访问该文件下的资源
app.use(express.static('/uploads'))

// 加载图片
app.use("/uploads", (req, res) => {
    let path = `uploads/${req.query.p}`
    fs.readFile(path, function (err, data) {
        if (err)
            res.send(err)
        else
            res.send(data)
    })
})
// 配置自定义处理中间件
app.use((req, res, next) => {
    res.cc = (msg, status = 501) => {
        return res.json({
            status,
            msg
        })
    }
    next()
})

app.use('/api', userRouter)
app.use(articleRouter)
app.use('/cate', cateRouter)

// 配置错误处理中间件
app.use(function (err, req, res, next) {
    if (err instanceof ValidationError) {
        return res.status(err.statusCode).json(err)
    }
    if (err.status === 401) {
        // 重新生成token ------  有技术了在做
        if (err.code === 'invalid_token') {
            // 过期的时间点
            let expiredAt = dayjs(err.inner.expiredAt)
            let now = dayjs()
            //过期了多久
            let expiration = now.diff(expiredAt, 'h')
            if (expiration < 24) {
                console.dir(req)
                // let token = jwt.sign()
            }
        } else
            return res.json({
                status: 401,
                msg: err.code
            })
    }
    return res.status(500).json(err)
})

app.listen(3001, () => {
    console.log("Server is 3001")
})